﻿using System.Collections.Generic;
using System.Threading;
using Phidgets;
using Phidgets.Events;

namespace Coding4Fun.Cannon.Robot
{
	public class PhidgetInterfaceKit
	{
		private static InterfaceKit _ifController;
		readonly AutoResetEvent _waitForLoad = new AutoResetEvent(false); // prevent race event to be sure phidgets fully loaded and online
		private const int TotalRelays = 4;

		public PhidgetInterfaceKit() 
		{
			if (_ifController != null)
				return;

			_ifController = new InterfaceKit();

			_ifController.Attach += _relayController_Attach;
			_waitForLoad.Reset();
			_ifController.open();
		}

		private static bool _isLoaded;
		void _relayController_Attach(object sender, AttachEventArgs e)
		{
			_isLoaded = true;
			_waitForLoad.Set();
		}

		public void Open(int index)
		{
			UseRelay(index, true);
		}

		public void Open(List<int> indexes)
		{
			foreach (var index in indexes)
				Open(index);
		}

		public void Close(int index)
		{
			UseRelay(index, false);
		}

		public void Close(List<int> indexes)
		{
			foreach (var index in indexes)
				Close(index);
		}
		
		private static bool IsValidIndex(int index)
		{
			return (index < TotalRelays || index >= 0);
		}

		private void UseRelay(int index, bool openRelay)
		{
			if (!IsValidIndex(index))
				return;

			if (!_isLoaded)
				_waitForLoad.WaitOne();

			_ifController.outputs[index] = openRelay;
		}
	}
}


